<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>异步链式调用示例</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f0f0f0;
            color: #333;
            padding: 20px;
            margin: 0;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        h1 {
            text-align: center;
            color: #2c3e50;
        }

        .log {
            background-color: #ecf0f1;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
            font-size: 16px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            white-space: pre-wrap;
        }

        .log span {
            color: #3498db;
        }

        .button {
            display: block;
            width: 100%;
            padding: 12px;
            margin-top: 20px;
            font-size: 16px;
            background-color: #3498db;
            color: #fff;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-align: center;
        }

        .button:hover {
            background-color: #2980b9;
        }
    </style>
</head>

<body>

    <div class="container">
        <h1>异步链式调用演示</h1>
        <div id="log" class="log">
            <span>正在等待输出...</span>
        </div>
        <button class="button" id="startButton">开始执行异步链式调用</button>
    </div>

    <script>
        const chainAsync = handlers => {
            let cur = 0;
            const last = handlers[handlers.length - 1];
            const next = () => {
                const fn = handlers[cur++];
                return fn === last ? fn() : fn(next);
            };
            next();
        };

        const logMessage = (message) => {
            const logContainer = document.getElementById('log');
            logContainer.innerText += `\n${message}`;
        };

        document.getElementById('startButton').addEventListener('click', () => {
            chainAsync([
                next => {
                    logMessage('0 秒后输出');
                    setTimeout(next, 1000);
                },
                next => {
                    logMessage('1 秒后输出');
                    setTimeout(next, 1000);
                },
                () => {
                    logMessage('2 秒后输出');
                }
            ]);
        });
    </script>

</body>

</html>